<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>PDF转Word在线工具</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Microsoft YaHei', Arial, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 20px;
        }

        .container {
            background: white;
            border-radius: 20px;
            box-shadow: 0 20px 40px rgba(0,0,0,0.1);
            padding: 40px;
            max-width: 600px;
            width: 100%;
            text-align: center;
        }

        .header h1 {
            color: #333;
            font-size: 2.5em;
            margin-bottom: 10px;
            background: linear-gradient(45deg, #667eea, #764ba2);
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
        }

        .header p {
            color: #666;
            font-size: 1.1em;
            margin-bottom: 30px;
        }

        .upload-area {
            border: 3px dashed #ddd;
            border-radius: 15px;
            padding: 40px 20px;
            margin: 30px 0;
            transition: all 0.3s ease;
            cursor: pointer;
            background: #fafafa;
        }

        .upload-area:hover {
            border-color: #667eea;
            background: #f0f4ff;
        }

        .upload-area.dragover {
            border-color: #667eea;
            background: #e8f2ff;
            transform: scale(1.02);
        }

        .upload-icon {
            font-size: 4em;
            color: #ddd;
            margin-bottom: 20px;
        }

        .upload-text {
            color: #666;
            font-size: 1.2em;
            margin-bottom: 15px;
        }

        .file-input {
            display: none;
        }

        .options {
            background: #f8f9fa;
            border-radius: 10px;
            padding: 20px;
            margin: 20px 0;
            text-align: left;
        }

        .options h3 {
            color: #333;
            margin-bottom: 15px;
            text-align: center;
        }

        .option-group {
            margin: 15px 0;
        }

        .option-group label {
            display: block;
            color: #666;
            margin-bottom: 5px;
            font-weight: bold;
        }

        .option-group input {
            width: 100%;
            padding: 8px 12px;
            border: 2px solid #ddd;
            border-radius: 5px;
            font-size: 1em;
        }

        .btn {
            background: linear-gradient(45deg, #667eea, #764ba2);
            color: white;
            border: none;
            padding: 12px 30px;
            border-radius: 25px;
            font-size: 1.1em;
            cursor: pointer;
            transition: all 0.3s ease;
            margin: 10px;
        }

        .btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 10px 20px rgba(102, 126, 234, 0.3);
        }

        .btn:disabled {
            background: #ccc;
            cursor: not-allowed;
            transform: none;
        }

        .progress {
            display: none;
            margin: 20px 0;
        }

        .progress-bar {
            width: 100%;
            height: 8px;
            background: #f0f0f0;
            border-radius: 4px;
            overflow: hidden;
        }

        .progress-fill {
            height: 100%;
            background: linear-gradient(45deg, #667eea, #764ba2);
            width: 0%;
            transition: width 0.3s ease;
        }

        .result {
            display: none;
            padding: 20px;
            margin: 20px 0;
            border-radius: 10px;
        }

        .result.success {
            background: #e8f5e8;
            border: 2px solid #4caf50;
            color: #2e7d32;
        }

        .result.error {
            background: #ffe8e8;
            border: 2px solid #f44336;
            color: #c62828;
        }

        .file-info {
            display: none;
            background: #f8f9fa;
            border-radius: 10px;
            padding: 20px;
            margin: 20px 0;
            text-align: left;
        }

        .tips {
            background: #fff3cd;
            border: 1px solid #ffeaa7;
            border-radius: 10px;
            padding: 15px;
            margin: 20px 0;
            text-align: left;
        }

        .tips h4 {
            color: #856404;
            margin-bottom: 10px;
        }

        .tips ul {
            color: #856404;
            padding-left: 20px;
        }

        @media (max-width: 768px) {
            .container {
                padding: 20px;
                margin: 10px;
            }
            
            .header h1 {
                font-size: 2em;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>📄 PDF转Word工具</h1>
            <p>快速将PDF文件转换为可编辑的Word文档</p>
        </div>

        <div class="upload-area" id="uploadArea">
            <div class="upload-icon">📁</div>
            <div class="upload-text">点击选择PDF文件或拖拽到此处</div>
            <div style="color: #999; font-size: 0.9em;">支持最大50MB的PDF文件</div>
            <input type="file" id="fileInput" class="file-input" accept=".pdf">
        </div>

        <div class="options">
            <h3>⚙️ 转换选项</h3>
            <div class="option-group">
                <label for="startPage">起始页面 (可选，从1开始):</label>
                <input type="number" id="startPage" min="1" placeholder="留空表示从第1页开始">
            </div>
            <div class="option-group">
                <label for="endPage">结束页面 (可选):</label>
                <input type="number" id="endPage" min="1" placeholder="留空表示转换到最后一页">
            </div>
        </div>

        <div class="file-info" id="fileInfo">
            <h3>📋 文件信息</h3>
            <div id="fileDetails"></div>
        </div>

        <div class="progress" id="progress">
            <div style="margin-bottom: 10px; color: #666;" id="progressText">处理中...</div>
            <div class="progress-bar">
                <div class="progress-fill" id="progressFill"></div>
            </div>
        </div>

        <div class="result" id="result">
            <div id="resultMessage"></div>
        </div>

        <div style="margin: 30px 0;">
            <button class="btn" id="analyzeBtn" onclick="analyzeFile()" disabled>🔍 分析PDF</button>
            <button class="btn" id="convertBtn" onclick="convertFile()" disabled>🔄 开始转换</button>
        </div>

        <div class="tips">
            <h4>💡 使用说明</h4>
            <ul>
                <li>支持文本型PDF和扫描版PDF转换</li>
                <li>扫描版PDF会保留图片，文字需要OCR识别</li>
                <li>转换时间取决于文件大小和复杂度</li>
                <li>转换完成后会自动下载Word文档</li>
            </ul>
        </div>

        <div style="text-align: center; margin: 30px 0; padding: 20px; background: #e8f4fd; border-radius: 10px;">
            <h4 style="color: #0066cc; margin-bottom: 15px;">🚀 开发者工具</h4>
            <p style="color: #666; margin-bottom: 15px;">需要集成API到您的应用中？查看完整的接口文档和在线测试工具</p>
            <a href="/api-demo" class="btn" style="text-decoration: none;">📋 API接口演示</a>
        </div>
    </div>

    <script>
        let selectedFile = null;
        const uploadArea = document.getElementById('uploadArea');
        const fileInput = document.getElementById('fileInput');
        const fileInfo = document.getElementById('fileInfo');
        const progress = document.getElementById('progress');
        const result = document.getElementById('result');
        const analyzeBtn = document.getElementById('analyzeBtn');
        const convertBtn = document.getElementById('convertBtn');

        // 文件上传处理
        uploadArea.addEventListener('click', () => fileInput.click());
        uploadArea.addEventListener('dragover', handleDragOver);
        uploadArea.addEventListener('dragleave', handleDragLeave);
        uploadArea.addEventListener('drop', handleDrop);
        fileInput.addEventListener('change', handleFileSelect);

        function handleDragOver(e) {
            e.preventDefault();
            uploadArea.classList.add('dragover');
        }

        function handleDragLeave(e) {
            e.preventDefault();
            uploadArea.classList.remove('dragover');
        }

        function handleDrop(e) {
            e.preventDefault();
            uploadArea.classList.remove('dragover');
            const files = e.dataTransfer.files;
            if (files.length > 0) {
                handleFile(files[0]);
            }
        }

        function handleFileSelect(e) {
            const file = e.target.files[0];
            if (file) {
                handleFile(file);
            }
        }

        function handleFile(file) {
            if (file.type !== 'application/pdf') {
                showResult('error', '请选择PDF文件！');
                return;
            }

            if (file.size > 50 * 1024 * 1024) {
                showResult('error', '文件大小超过50MB限制！');
                return;
            }

            selectedFile = file;
            showFileInfo(file);
            analyzeBtn.disabled = false;
            convertBtn.disabled = false;
            hideResult();
        }

        function showFileInfo(file) {
            document.getElementById('fileDetails').innerHTML = `
                <p><strong>文件名:</strong> ${file.name}</p>
                <p><strong>文件大小:</strong> ${formatFileSize(file.size)}</p>
                <p><strong>文件类型:</strong> ${file.type}</p>
            `;
            fileInfo.style.display = 'block';
        }

        function formatFileSize(bytes) {
            if (bytes === 0) return '0 Bytes';
            const k = 1024;
            const sizes = ['Bytes', 'KB', 'MB', 'GB'];
            const i = Math.floor(Math.log(bytes) / Math.log(k));
            return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
        }

        function showProgress(text) {
            document.getElementById('progressText').textContent = text;
            progress.style.display = 'block';
            
            let width = 0;
            const interval = setInterval(() => {
                width += Math.random() * 10;
                if (width > 90) width = 90;
                document.getElementById('progressFill').style.width = width + '%';
            }, 200);
            
            return interval;
        }

        function hideProgress() {
            progress.style.display = 'none';
            document.getElementById('progressFill').style.width = '0%';
        }

        function showResult(type, message) {
            result.className = `result ${type}`;
            result.style.display = 'block';
            document.getElementById('resultMessage').innerHTML = message;
        }

        function hideResult() {
            result.style.display = 'none';
        }

        async function analyzeFile() {
            if (!selectedFile) return;

            const progressInterval = showProgress('正在分析PDF文件...');
            analyzeBtn.disabled = true;

            try {
                const formData = new FormData();
                formData.append('file', selectedFile);

                const response = await fetch('/api/analyze', {
                    method: 'POST',
                    body: formData
                });

                const data = await response.json();
                
                clearInterval(progressInterval);
                document.getElementById('progressFill').style.width = '100%';
                
                setTimeout(() => {
                    hideProgress();
                    
                    if (data.success) {
                        const info = data.info;
                        let message = `
                            <h3>📊 分析结果</h3>
                            <p><strong>页数:</strong> ${info.pages}</p>
                            <p><strong>包含文本:</strong> ${info.has_text ? '是' : '否'}</p>
                            <p><strong>包含图片:</strong> ${info.has_images ? '是' : '否'}</p>
                        `;
                        
                        if (info.title) {
                            message += `<p><strong>标题:</strong> ${info.title}</p>`;
                        }
                        
                        if (!info.has_text && info.has_images) {
                            message += `<p style="color: #ff9800; margin-top: 10px;">⚠️ 这是扫描版PDF，转换后需要OCR识别文字</p>`;
                        }
                        
                        showResult('success', message);
                    } else {
                        showResult('error', '分析失败: ' + data.error);
                    }
                    
                    analyzeBtn.disabled = false;
                }, 500);

            } catch (error) {
                clearInterval(progressInterval);
                hideProgress();
                showResult('error', '分析失败: ' + error.message);
                analyzeBtn.disabled = false;
            }
        }

        async function convertFile() {
            if (!selectedFile) return;

            const progressInterval = showProgress('正在转换PDF文件，请稍候...');
            convertBtn.disabled = true;

            try {
                const formData = new FormData();
                formData.append('file', selectedFile);
                
                const startPage = document.getElementById('startPage').value;
                const endPage = document.getElementById('endPage').value;
                
                if (startPage) {
                    formData.append('start_page', parseInt(startPage) - 1);
                }
                if (endPage) {
                    formData.append('end_page', parseInt(endPage));
                }

                const response = await fetch('/api/convert', {
                    method: 'POST',
                    body: formData
                });

                clearInterval(progressInterval);
                document.getElementById('progressFill').style.width = '100%';

                if (response.ok) {
                    const blob = await response.blob();
                    const filename = selectedFile.name.replace('.pdf', '.docx');

                    const url = window.URL.createObjectURL(blob);
                    const a = document.createElement('a');
                    a.href = url;
                    a.download = filename;
                    document.body.appendChild(a);
                    a.click();
                    document.body.removeChild(a);
                    window.URL.revokeObjectURL(url);

                    setTimeout(() => {
                        hideProgress();
                        showResult('success', `
                            <h3>🎉 转换成功！</h3>
                            <p>文件已开始下载: <strong>${filename}</strong></p>
                            <p>文件大小: ${formatFileSize(blob.size)}</p>
                        `);
                        convertBtn.disabled = false;
                    }, 500);

                } else {
                    const errorData = await response.json();
                    throw new Error(errorData.error || '转换失败');
                }

            } catch (error) {
                clearInterval(progressInterval);
                hideProgress();
                showResult('error', '转换失败: ' + error.message);
                convertBtn.disabled = false;
            }
        }
    </script>
</body>
</html>